package hasthi.tools.analyze;

import java.util.Random;

import org.apache.xmlbeans.XmlObject;
import org.xmlpull.v1.builder.XmlElement;

import xsul.invoker.soap_over_http.SoapHttpDynamicInfosetInvoker;
import xsul.xbeans_util.XBeansUtil;

public class PerfClient implements Runnable{
    private XmlElement message;
    private SoapHttpDynamicInfosetInvoker invoker;
    private int repeatCount;
    private int meanWaitTime = 100;
    private DataCollector dataCollector; 
    private PerfResponseVerifier verifier;
    private Random r = new Random();
    private String id;
    private long testEndTime = Long.MAX_VALUE;
    
    public PerfClient(String id,String serviceUrl,int repeatCount,int meanWaitTime, PerfResponseVerifier verifier,XmlObject message){
        invoker = new SoapHttpDynamicInfosetInvoker(serviceUrl);
        this.repeatCount = repeatCount;
        this.meanWaitTime = meanWaitTime;
        dataCollector = new DataCollector("perfClient");
        this.verifier = verifier;
        this.id = id;
        this.message = XBeansUtil.xmlObjectToXmlElement(message);
    }
    public void run() {
        try {
            for(int i = 0;i<repeatCount;i++){
                try {
                    if(System.currentTimeMillis() > testEndTime){
                        break;
                    }
                    dataCollector.startClock();
                    XmlElement response = invoker.invokeMessage(message);
                    dataCollector.endClock();
                    if(!verifier.verify(XBeansUtil.xmlElementToXmlObject(response))){
                        dataCollector.notifyFaluire();
                    }
                } catch (Throwable e) {
                    dataCollector.endClock();
                    e.printStackTrace();
                    dataCollector.notifyFaluire();
                }
                if(i % 10 ==0){
                    System.out.println(id + " " + i);
                }
                Thread.sleep((long)(Math.abs(meanWaitTime*r.nextGaussian())/2));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            System.out.println("Client "+ id + " Done");
//            try {
//                dataCollector.sendData();
//            } catch (HasthiException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
        }
    }
    
    public static interface PerfResponseVerifier{
        public boolean verify(XmlObject response);
    }

    public DataCollector getDataCollector() {
        return dataCollector;
    }
    public void setTestEndTime(long testEndTime) {
        this.testEndTime = testEndTime;
    }
    
    

}
